<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebView消息端口示例</title>
</head>
<body>
<h2>WebView消息端口示例</h2>
<div>
    <input type="button" value="发送给Ets" onclick="PostMsgToEts(msgFromJS.value);"/><br/>
    <input id="msgFromJS" type="text" value="将此消息从HTML发送到ets"/><br/>
</div>
<p class="output">显示从ets发送的已接收消息</p>
</body>
<script>
var h5Port;
var output = document.querySelector('.output');
window.addEventListener('message', function (event) {
    if (event.data === '__init_port__') {
        if (event.ports[0] !== null) {
            // 1. 保存从应用侧发送过来的端口。
            h5Port = event.ports[0];
            h5Port.onmessage = function (event) {
              // 2. 接收ets侧发送过来的消息。
              var msg = '从ets收到消息:';
              var result = event.data;
              if (typeof(result) === 'string') {
                console.info(`received string message from html5, string is: ${result}`);
                msg = msg + result;
              } else if (typeof(result) === 'object') {
                if (result instanceof ArrayBuffer) {
                  console.info(`received arraybuffer from html5, length is: ${result.byteLength}`);
                  msg = msg + 'lenght is ' + result.byteLength;
                } else {
                  console.info('not support');
                }
              } else {
                console.info('not support');
              }
              output.innerHTML = msg;
            }
        }
    }
})
// 3. 使用h5Port向应用侧发送消息。
function PostMsgToEts(data) {
    if (h5Port) {
      h5Port.postMessage(data);
    } else {
      console.error('h5Port is null, Please initialize first');
    }
}

</script>
</html>